package fl.ass.service.service.impl;

import cmm.mid.core.framework.dto.DataResultDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.fl.capital.condition.CapFundDecomposeQueryCondition;
import cn.fl.capital.service.ICapFundVfDtlApiService;
import cn.fl.capital.service.IProfitAndLossApiService;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import com.alibaba.fastjson.JSON;
import fl.ass.facade.condition.AssTrailCarDInfQueryCondition;
import fl.ass.facade.condition.AssTrailCarDQueryCondition;
import fl.ass.facade.dto.AssDealSellDTO;
import fl.ass.facade.dto.AssTrailCarDDTO;
import fl.ass.service.dao.AssTrailCarDInfMapper;
import fl.ass.service.po.AssTrailCarDInf;
import fl.ass.service.service.IAssCapFundDecomposeService;
import fl.ass.service.service.IAssDealSellService;
import fl.ass.service.service.IAssTrailCarDService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.dto.FlowCompleteParamsDTO;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import fl.flow.service.flow.service.ISysFlowSHService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class AssCapFundDecomposeServiceImpl implements IAssCapFundDecomposeService {

    private static final Logger log = LoggerFactory.getLogger(IAssCapFundDecomposeService.class);

    /**
     * 拖车明细服务
     */
    @Autowired
    private IAssTrailCarDService assTrailCarDService;

    /**
     * 拖车申请服务
     */
    @Autowired
    private AssTrailCarDInfMapper assTrailCarDInfMapper;

    /**
     * 客户资金核销记录表 模块对外暴露服务接口
     */
    @Autowired
    private ICapFundVfDtlApiService capFundVfDtlApiService;

    @Autowired
    private IProfitAndLossApiService profitAndLossApiService;

    @Autowired
    private ISysFlowSHService sysFlowSHService;

    /**
     * 流处置变卖服务
     */
    @Autowired
    private IAssDealSellService assDealSellService;

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

    /**
     * REQ-2334 流程优化
     * 根据流程发起时间，判断是否为新流程
     * @param flowCompleteParamsDTO
     * @return
     * @throws BaseException
     */
    @Override
    public boolean isTheNewestFlow(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
        boolean flag = true;

        SysFlowSHQueryCondition qc = new SysFlowSHQueryCondition();
        qc.setSysCd(flowCompleteParamsDTO.getSysCd());//系统代码
        qc.setWordsInTheTable("ASS");//表中字
        qc.setDataId(flowCompleteParamsDTO.getBusinessKey());//业务主键
        qc.setpDefKey(flowCompleteParamsDTO.getProcDefKey());
        qc.setStatus(BaseConstant.IS_YESNO_YES);
        qc.setpInstId(flowCompleteParamsDTO.getProcInstId());
        List<SysFlowSHDTO> searchList = this.sysFlowSHService.searchList(qc);
        if (CollectionUtils.isNotEmpty(searchList)) {
            SysFlowSHDTO sysFlowSHDTO = searchList.get(0);
            Date oldDate = DateUtils.formatDate(sysFlowSHDTO.getpCrtTm(), DateUtils.YYYY_MM_DDHHMMSS);
            Date newDate = DateUtils.formatStringToDate("2019-06-20 19:20:44", DateUtils.YYYY_MM_DDHHMMSS);
            if (oldDate.compareTo(newDate) < 0) {
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public void capFundDecompose(FlowCompleteParamsDTO flowCompleteParamsDTO) {

        //业务主键id
        Long id = flowCompleteParamsDTO.getBusinessKey();
        BaseLogUtils.newLogger("资金分解&计算损益Start").setBussinessId(JSON.toJSONString(id)).info();
        AssDealSellDTO assDealSellDTO = this.assDealSellService.selectById(id);

        if(assDealSellDTO == null || assDealSellDTO.getDetailId() == null) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "查询处置-变卖信息明细表失败.");
        }
        Long detailId = assDealSellDTO.getDetailId();

        AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
        qc.setId(detailId);
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        qc.setIsHis(BaseConstant.IS_YESNO_NO);
        AssTrailCarDDTO assTrailCarDDTO = assTrailCarDService.selectOne(qc);

        if(assTrailCarDDTO == null || assTrailCarDDTO.getPaySchId() == null) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "查询拖车信息明细表失败.");
        }

        AssTrailCarDInfQueryCondition con = new AssTrailCarDInfQueryCondition();
        con.setDetailId(detailId);
        List<AssTrailCarDInf> list = assTrailCarDInfMapper.selectList(con);
        if (CollectionUtils.isEmpty(list)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "查询拖车实际信息明细表失败.");
        }
        Date actBackDt = list.get(0).getActBackDt();
        if(actBackDt == null) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "拖车实际信息明细表的实际拖回日期为空.");
        }
        // 根据拖车支付表查启用支付表用以核销
        List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = prjPrdPaySchMApiService.selectEnabledListByPaySchId(assTrailCarDDTO.getPaySchId());
        if (CollectionUtils.isEmpty(prjPrdPaySchMDTOS)) {
            throw new BaseException("查不到启用支付表");
        }
        Long enabledPaySchId = prjPrdPaySchMDTOS.get(0).getId();
        CapFundDecomposeQueryCondition condition = new CapFundDecomposeQueryCondition();
        condition.setPaySchId(enabledPaySchId);// 支付表ID
        // 获取流程发起时间
        List<SysFlowSHDTO> sysFlowSHDTOS = this.assTrailCarDService.getSysFlowSHDTOS(id);
        condition.setFlowStartTm(sysFlowSHDTOS.get(0).getpCrtTm());
        condition.setBackDate(actBackDt);// 赎回结清 车辆拖回时间
        /**
         * 业务类型
         * 1.重卡正常、提前、特殊放款分解首期款
         * 2.添加风险保证金流程，分解风险保证金
         * 3.续保流程，分解保险保证金
         * 4.重卡、卡云、汽车金融正常、提前结清流程，分解剩余费用项
         * 5.重卡城配放款流程，根据项目ID分解首期款
         * 6.拖车赎回结清
         * 7.拖车赎回转正常
         */
       /* condition.setBuTypCd(assDealRedeemDTO.getRedeemTypeCd().equals(InterfaceConstants.REDEEM_TYPE_CD_1) ? "6"
                : assDealRedeemDTO.getRedeemTypeCd().equals(InterfaceConstants.REDEEM_TYPE_CD_2) ? "7" : "");// 6.赎回结清
                                                                            // 7.赎回转正常*/

        condition.setBuTypCd("6");

        //condition.setDataId(id);// 流程中dataId
        condition.setDataId(assTrailCarDDTO.getPaySchId());

        condition.setCurrentUsrId(flowCompleteParamsDTO.getCrtUsrId());
        condition.setCurrentUsrNm(flowCompleteParamsDTO.getCrtUsrName());
        BaseLogUtils.newLogger("资金分解start").setKeys("condition:" + JSON.toJSONString(condition)).info();
        DataResultDTO resultTemp = this.capFundVfDtlApiService.autoFundDecompose(condition);

        // 资金成功失败
        if (BaseConstant.IS_YESNO_NO_STR.equals(resultTemp.getCode())) {
            throw new BaseException(resultTemp.getInfo());
        }
        BaseLogUtils.newLogger("资金分解end").setKeys("resultTemp:" + JSON.toJSONString(resultTemp)).info();
        // 资金成功分解
        if (BaseConstant.IS_YESNO_YES_STR.equals(resultTemp.getCode())) {
            BaseLogUtils.newLogger("支付信息明细表插入各项损益 start").setKeys("paySchId:" + JSON.toJSONString(assTrailCarDDTO.getPaySchId())).info();
            //计算损益
            profitAndLossApiService.addProfitAndLoss(assTrailCarDDTO.getPaySchId());
            BaseLogUtils.newLogger("支付信息明细表插入各项损益 end").setKeys("paySchId:" + JSON.toJSONString(assTrailCarDDTO.getPaySchId())).info();
        }
    }
}
